import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import qs from 'qs'
import store from '@/store'
import { getToken } from '@/utils/auth'
import codeConfig from '@/utils/codeConfig'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 当跨域请求时发送cookie
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    // 'Content-Type': 'application/json',
  }
})

// 请求拦截
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    // POST传参序列化
    if (config.method === 'post') {
      config.data = qs.stringify(config.data)
    } else if (config.method === 'get') {
      let _params = ''
      for (const key in config.data) {
        _params += `${key}=${config.data[key]}`
      }
      config.url = `${config.url}?${_params}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== codeConfig.HTTP_SUCCESS) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('您已经登出，您可以取消以继续停留在此页面，或重新登录', '登出确认', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
